import { getStoreDetail } from "@/api/stores";
import { getAgentDetail } from "@/api/agent";
import { getChannelList } from "@/api/channel";

const state = () => {
  return {
    userInfo: {},
    agentInfo: {},
    channelInfo: {},
    urlQuery: {},
  };
};

const mutations = {
  setUserInfo(state, data) {
    state.userInfo = data;
  },
  setAgentInfo(state, data) {
    state.agentInfo = data;
  },
  setChannelInfo(state, data) {
    state.channelInfo = data;
  },
  setUrlQuery(state, data) {
    state.urlQuery = data;
  },
};

const actions = {
  setStoreInfo(context, data) {
    return new Promise((resolve) => {
      getStoreDetail(data.id).then((res) => {
        if (res.code == 200) {
          res.data.tenantId = data.tenantId;
          context.commit("setUserInfo", res.data);
          context.commit("setStep1", res.data);
          context.commit("setStep2", res.data);
          context.commit("setAcquiring", res.data);
          context.dispatch("getAgentInfo", res.data.agentId);
          resolve(res.data);
        }
      });
    });
  },
  getAgentInfo(context, id) {
    getAgentDetail(id).then((res) => {
      if (res.code == 200) {
        context.commit("setAgentInfo", res.data);
        context.dispatch("getChannelInfo", res.data.channelCode);
      }
    });
  },
  getChannelInfo(context, channelCode) {
    getChannelList(1, 10, {
      channelCode,
    }).then((res) => {
      if (res.code == 200) {
        context.commit("setChannelInfo", res.data.records[0]);
      }
    });
  },
  setNewStoreInfo(context, data) {
    return new Promise((resolve) => {
      getStoreDetail(data.id).then((res) => {
        if (res.code == 200) {
          res.data.tenantId = data.tenantId;
          context.commit("setUserInfo", res.data);
          context.commit("setStep1", res.data);
          context.commit("setStep2", res.data);
          context.commit("setAcquiring", res.data);
          context.dispatch("setNewAgentInfo", res.data.agentId);
          context.dispatch("getChannelInfo", res.data.defaultChannelCode);
          resolve(res.data);
        }
      });
    });
  },
  setNewAgentInfo(context, id) {
    getAgentDetail(id).then((res) => {
      if (res.code == 200) {
        context.commit("setAgentInfo", res.data);
      }
    });
  },
};

export default {
  namespace: true,
  state,
  mutations,
  actions,
};
